/*
 * Project: book_manage
 * 
 * File Created at 2017年9月6日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.web;


import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.whb.book.common.ActionResponse;
import com.whb.book.common.ResMsg;
import com.whb.book.common.sensitive.SensitiveWordFilter;
import com.whb.book.entity.Book;
import com.whb.book.service.BookService;

/**
 * @Type BookAction.java
 * @Desc 
 * @author wanghb
 * @date 2017年9月6日 下午10:43:19
 * @version JDK 1.8
 */
@Controller
public class BookAction {
    
    private static Logger logger = LoggerFactory.getLogger(BookAction.class);
    
    @Autowired
    private BookService bookService;
    
    @Autowired
    private SensitiveWordFilter sensitive;
    
    /**
     * 
     * bookList:(). <br/>
     * 
     * 
     * @author wanghb
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @since JDK 1.8
     */
    @RequestMapping(value = "/bookList",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ActionResponse bookList(HttpServletRequest request){
        ActionResponse ar = new ActionResponse();
        List<Book> list = bookService.findBookList();
        System.out.println();
        ar.setDataInResult(list);
        return ar;
    }
    
    /**
     * 
     * findBookById:(). <br/>
     * 
     * 
     * @author wanghb
     * @param request
     * @return
     * @since JDK 1.8
     */
    @RequestMapping(value = "/findBookById",produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ActionResponse findBookById(HttpServletRequest request){
        ActionResponse ar = new ActionResponse();
        String id = request.getParameter("id");
        if(StringUtils.isBlank(id)){
            logger.warn("入参id为空");
            ar.setStatusAndMessage(ResMsg.PARAM_ERROR.getCode(), ResMsg.PARAM_ERROR.getMsg());
            return ar;
        }
        if(sensitive.isSensitive(id)){
            logger.warn("输入框中={}含有敏感词",id);
            ar.setStatusAndMessage(ResMsg.SENSITIVE_ERROR.getCode(), ResMsg.SENSITIVE_ERROR.getMsg());
            return ar;
        }
        Book book = bookService.findBookById(Long.valueOf(id));
        ar.setResult(book);
        return ar;
    }
    
    /**
     * 
     * uploadFileData:(). <br/>
     * 
     * 上传文件（这里是上传apk）
     * @author wanghb
     * @param request
     * @return
     * @since JDK 1.8
     * 
     * MediaType.TEXT_PLAIN_VALUE:避免IE8当返回前端数据为json时出现下载的情况
     */
    @RequestMapping(value = "/uploadApk",produces = {MediaType.TEXT_PLAIN_VALUE +";application/json;charset=utf-8"})
    public String uploadFileData(@RequestParam("uploadfile") CommonsMultipartFile file,
                                 HttpServletRequest request, HttpServletResponse response) {
        ActionResponse ar = new ActionResponse();
        String fileName = file.getOriginalFilename();
        String suffix = "";
        if (StringUtils.isNotEmpty(fileName)) {
            suffix = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
            if (!"apk".equals(suffix)) {
                logger.error("上传文件错误 {}", fileName);
                ar.setStatusAndMessage(ResMsg.FILE_ERROR.getCode(),
                        ResMsg.FILE_ERROR.getMsg());
                return JSON.toJSONString(ar);
            }
            String path = request.getSession().getServletContext()
                    .getRealPath("/download/" + fileName);
            File destFile = new File(path);
            //向app表里下载字段赋值(辽宁需求)
            //            App app = new App();
            //            app.setAndoridDownUrl("");
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), destFile); //优雅的关闭
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    /**
     * 
     * uploadFileDatas:(). <br/>
     * 
     * 上传文件（这里是上传apk）
     * @author wanghb
     * @param request
     * @return
     * @since JDK 1.8
     */
    @RequestMapping(value = "/uploadApks",produces = {MediaType.TEXT_PLAIN_VALUE +";application/json;charset=utf-8"})
    public String uploadFileDatas(@RequestParam("uploadfile") CommonsMultipartFile[] files,
                                  HttpServletRequest request, HttpServletResponse response) {
        // MultipartFile是对当前上传的文件的封装，当要同时上传多个文件时，可以给定多个MultipartFile参数(数组)
        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getOriginalFilename();
            String suffix = "";
            if (StringUtils.isNotEmpty(fileName)) {
                suffix = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
                if (!"apk".equals(suffix)) {
                    return "apk文件错误";
                }
                //String appName=  UUID.randomUUID().toString().replace("-", "") + "." + suffix;
                String path = request.getSession().getServletContext()
                        .getRealPath("/download/" + fileName);
                File destFile = new File(path);
                //向app表里下载字段赋值
                //App app = new App();
                //app.set();
                try {
                    FileUtils.copyInputStreamToFile(files[i].getInputStream(), destFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return "";
    }

    public static void main(String[] args) {
        String aString = "aaaa.apk";
        System.out.println(aString.substring(aString.indexOf(".")));
        System.out.println(aString.substring(aString.indexOf(".") + 1, aString.length()));
        System.out.println(UUID.randomUUID().toString().replace("-", ""));
    }
}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月6日 wanghb create
 */